﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace TileSplitter
{
    class Program
    {
        static void Main(string[] args)
        {

            int tileWidth = 32;
            int tileHeight = 32;


            string originalFile = args[0];
            string tileNamePart = Path.GetFileNameWithoutExtension(originalFile);

            var tileSet = Image.FromFile(originalFile);


            int x = 0, y = 0;

            int height = tileSet.Height;
            int width = tileSet.Width;

            int tileNr = 1;

            Console.Write("Working");

            while (y + tileHeight < height)
            {
                x=0;
                while (x + tileWidth < width)
                {

                    using (Bitmap tile = new Bitmap(tileWidth, tileHeight, tileSet.PixelFormat))
                    {
                        using (Graphics g = Graphics.FromImage(tile))
                        {
                            Rectangle srcRect = new Rectangle(x, y, tileWidth, tileHeight);
                            g.DrawImage(tileSet, 0, 0, srcRect, GraphicsUnit.Pixel);
                        }

                        bool allTransparent = true;
                        for (int px = 0; px < tileWidth; px++)
                        {
                            for (int py =0; py< tileHeight; py++)
                            {
                                Color pc = tile.GetPixel(px, py);
                                if (pc.A > 0)
                                {
                                    allTransparent = false;
                                    break;
                                }
                            }
                        }

                        if (!allTransparent)
                        {
                            string tileName = tileNamePart + "-" + tileNr.ToString("0000") + "-(" + (x / 32) + "-" + (y / 32) + ").png";
                            tile.Save(tileName, ImageFormat.Png);

                            tileNr++;

                            Console.Write(".");
                        }
                    }

                    x += tileWidth;

                }

                y += tileHeight;

            }

            Console.WriteLine();


        }
    }
}
